package com.rmb.util;

import com.rmb.entity.SourceEntity;
import com.ruoyi.common.utils.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZhaoMuYang
 * @date 2021年1月8日
 */
public class RedisConnector {

    public static final String REDIS = "redis";

    public static Map<Long, Jedis> redisPoolMap = new ConcurrentHashMap<>(16);

    public static Jedis getRedisConnection(SourceEntity dataSource) {
        if (StringUtils.isEmpty(dataSource.getHost()) && StringUtils.isNull(dataSource.getPort())) {
            return null;
        }
        if (redisPoolMap.containsKey(dataSource.getId())) {
            return redisPoolMap.get(dataSource.getId());
        }
        Jedis jedis = new Jedis(dataSource.getHost(), dataSource.getPort());
        if(dataSource.getPassword()!=null){
            jedis.auth(dataSource.getPassword());
        }
        redisPoolMap.put(dataSource.getId(),jedis);
        return jedis;
    }

    /**
     * 初始化所有连接
     *
     * @param dataSources 数据源集合
     */
    public static void initRedisPoolMap(List<SourceEntity> dataSources) {
        dataSources.forEach(dataSource -> {
            if (dataSource.getSourceType().equals(REDIS)) {
                Jedis jedis = new Jedis(dataSource.getHost(), dataSource.getPort());
                if(dataSource.getPassword()!=null){
                    jedis.auth(dataSource.getPassword());
                }
                redisPoolMap.put(dataSource.getId(), jedis);
            }
        });
    }

    /**
     * 关闭所有redis连接
     */
    public static void closeAll() {
        redisPoolMap.keySet().forEach(RedisConnector::close);
    }

    /**
     * 关闭连接
     *
     * @param id redis数据源id
     */
    public static void close(Long id) {
        synchronized (redisPoolMap.get(id)) {
            redisPoolMap.get(id).close();
        }
    }

    /**
     * 测试redis连接
     *
     * @param dataSource 数据源
     */
    public static boolean isConnected(SourceEntity dataSource) {
        Jedis jedis = null;
        boolean isConnected = true;
        try {
            if(dataSource.getId() != null && redisPoolMap.containsKey(dataSource.getId())){
                jedis= redisPoolMap.get(dataSource.getId());
            }else{
                jedis=new Jedis(dataSource.getHost(), dataSource.getPort());
                if(dataSource.getPassword()!=null){
                    jedis.auth(dataSource.getPassword());
                }
            }
            jedis.ping();
        } catch (Exception e) {
            isConnected = false;
        }
        if(dataSource.getId() == null || !redisPoolMap.containsKey(dataSource.getId())){
            assert jedis != null;
            jedis.close();
        }
        return isConnected;
    }

}
